//
//  BrokenNetController.swift
//  d11
//

//  Copyright © 2018年 Tech_001. All rights reserved.
//

import Foundation
import UIKit
class BrokenNetController: UIViewController{
    @IBOutlet weak var hitNet: UILabel!
    @IBOutlet weak var segmentingLine: UIView!
    @IBOutlet weak var refurbished: UIButton!
    @IBOutlet weak var sportMotto: UILabel!
    @IBOutlet weak var sportName: UILabel!
    var bufWindows: [UIWindow] = []    //缓存window
  var delay: Double = 2.0  //延迟时间
    //网络环境监听控件的初始化
    let reachability = Reachability()!
    //网络环境监听控件的初始化
    override func viewDidLoad() {
        let backItem = UIBarButtonItem()
        backItem.title = ""
        //左侧按钮开始
        let button =   UIButton(type: .custom)
        button.frame = CGRect(x:0, y:0, width:22, height:22)
        button.setImage(UIImage(named:"header_broken_back"), for: .normal)
        //button.setTitle("返回", for: .normal)
       button.addTarget(self, action: #selector(backToPrevious), for: .touchUpInside)
        
        let leftBarBtn = UIBarButtonItem(customView: button)
        
        //用于消除左边空隙，要不然按钮顶不到最前面
//        let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil,
//                                     action: nil)
//        spacer.width = -30;
 ///       spacer,
        self.navigationItem.leftBarButtonItems = [leftBarBtn]
        //左侧按钮结束
        self.navigationItem.backBarButtonItem = backItem
        let topLogo = UIImage(named: "icon_nav_left_logo")
        let titleView = UIView()
        let topLogoView = UIImageView(image: topLogo)
        titleView.addSubview(topLogoView)
        topLogoView.contentMode = .scaleToFill
       topLogoView.frame = CGRect(x: -(137/2), y:-(35/2), width: 137, height: 35)
        navigationItem.titleView = titleView
         var motto_random:Int=0
        sportMotto.numberOfLines=0;
        sportMotto.font = UIFont.boldSystemFont(ofSize: 18)
        sportMotto.lineBreakMode = NSLineBreakMode.byClipping
        sportMotto.textAlignment = .left
        sportName.numberOfLines=1
        let path =  Bundle.main.path(forResource: "player_motto.json", ofType: nil)
        let data = NSData(contentsOfFile: path!)!
        do{
            let dictArr = try JSONSerialization.jsonObject(with:data as Data, options: JSONSerialization.ReadingOptions.mutableContainers)
            var i:Int=0;
            
            for dict in dictArr as! [String: [String]]
            {
              
                if(i==0){
                    motto_random = Int(arc4random_uniform(UInt32(dict.value.count)))
                    sportMotto.text=dict.value[motto_random]
                }else if(i==1){
                    sportName.text=dict.value[motto_random]
                }
                i=i+1
            }
        }catch{
            print("异常报错")
        }
        sportName.font = UIFont.boldSystemFont(ofSize: 18)
        sportName.textAlignment = .right
        self.view.addSubview(sportName)
        self.view.addSubview(sportMotto)
    }
    @objc func backToPrevious(){
          self.rmTopView()
    }
//    func readSportsData() -> NSData{
//        //读取文件的路径
//        let path =  Bundle.main.path(forResource: "player_motto.json", ofType: nil)
//        let data = NSData(contentsOfFile: path!)!
//        return data
//
//    }
    @IBAction func refurbishedClick(_ sender: Any) {
         let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)!
        requestUrl(urlString: url);
    }
    func requestUrl(urlString: String){
        var url: NSURL = NSURL(string: urlString)!
        let request: NSURLRequest = NSURLRequest(url:url as URL)
        
        NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main, completionHandler:{
            (response, data, error) -> Void in
            if ((error) != nil) {
              //  print("错误\(error)")
               
                self.showToast(text: "网络连接异常，请稍候再试", pos: .Bottom)
                
            }else{
                self.rmTopView()
            }
            
        })
    }
    //移除最上层界面
    func rmTopView(){
        dismiss(animated: true, completion: nil)
    }
    
    //启动当前网络环境结束
    enum Position: Int {
        case Top
        case Mid
        case Bottom
    }
    //显示toast
    func showToast(text: String, pos: Position) {
        let rootRect = UIApplication.shared.windows.first?.frame   //应用屏幕大小
        
        let container = UIView()   //全屏且透明，盖在最上面， 可以自定义点击事件， 从而实现模态和非模态框效果。
        container.backgroundColor = UIColor.clear
        container.frame = rootRect!
        
        let lableView = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        lableView.font = UIFont.systemFont(ofSize: 15)
        lableView.textColor = UIColor.white
        lableView.text = text
        lableView.textAlignment = .center
        lableView.numberOfLines = 1
        
        let rect = lableView.getLableSize(text: text, maxWidth: 300)
        
        print("\(rect.width)  \(rect.height)")
        
        let bgView = UIView()
        bgView.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0, alpha: 0.8)
        bgView.layer.cornerRadius = 10
        var bgRect: CGRect    //黑色半透明背景
        
        switch pos {
        case .Bottom:
            lableView.frame = CGRect(x: (rootRect?.width)!/2 - rect.width/2,
                                     y: (rootRect?.height)! - rect.height - 30 ,
                                     width: rect.width,
                                     height: rect.height)
            bgRect = CGRect(x: lableView.frame.minX - 5,
                            y: lableView.frame.minY - 5,
                            width: rect.width + 10,
                            height: rect.height + 10)
        case .Mid:
            lableView.frame = CGRect(x: (rootRect?.width)!/2 - rect.width/2,
                                     y: (rootRect?.height)!/2 - rect.height/2 ,
                                     width: rect.width,
                                     height: rect.height)
            bgRect = CGRect(x: lableView.frame.minX - 5,
                            y: lableView.frame.minY - 5,
                            width: rect.width + 10,
                            height: rect.height + 10)
        case .Top:
            lableView.frame = CGRect(x: (rootRect?.width)!/2 - rect.width/2,
                                     y: 80,
                                     width: rect.width,
                                     height: rect.height)
            
            bgRect = CGRect(x: lableView.frame.minX - 5,
                            y: lableView.frame.minY - 5,
                            width: rect.width + 10,
                            height: rect.height + 10)
        }
        bgView.frame = bgRect
        
        container.addSubview(bgView)
        container.addSubview(lableView)  //添加lableView
        
        let window = UIWindow()
        window.backgroundColor = UIColor.clear
        window.frame = rootRect!
        window.center = container.center
        window.windowLevel = UIWindow.Level.alert
        window.isHidden = false
        window.addSubview(container)
        
        //添加点击事件
        bgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapGesture(sender:))))
        
        bufWindows.append(window)
        perform(#selector(showFinished(sender:)), with: window, afterDelay: delay)
    }
    //toast超时关闭
    @objc func showFinished(sender: AnyObject) {
        if let window = sender as? UIWindow {
            if let index = bufWindows.index(of: window) {
                bufWindows.remove(at: index)  //删除
            }
        } else {
            //do nothing
        }
    }
    //添加点击事件
    @objc func tapGesture(sender: UITapGestureRecognizer) {
  
        
        //移除最后一个
        if bufWindows.count > 0 {
            bufWindows.removeLast()
        }
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    }
    
}
extension UILabel {
    //根据最大宽度计算宽高
    func getLableSize(text: String, maxWidth: CGFloat) -> CGRect {
        let maxSize = CGSize(width: maxWidth, height: 0)   //注意高度是0
        //    size = text.boundingRectWithSize(size2, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes , context: nil);
        let size = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin,
                                     attributes: [NSAttributedString.Key.font:self.font], context: nil)
        return size
        
    }
}
